<template>
  <div class="dashboard">
    <h2>绿植领养管理系统 - 仪表盘</h2>
    <div class="stats">
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>植物总数</span>
          </div>
        </template>
        <div class="stat-value">{{ plantCount }}</div>
      </el-card>
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>用户数量</span>
          </div>
        </template>
        <div class="stat-value">{{ userCount }}</div>
      </el-card>
      <el-card class="stat-card">
        <template #header>
          <div class="card-header">
            <span>订单总数</span>
          </div>
        </template>
        <div class="stat-value">{{ orderCount }}</div>
      </el-card>
    </div>
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>植物分类统计</span>
        </div>
      </template>
      <div ref="chartRef" style="height: 400px;"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { usePlantStore } from '@/stores/plantStore';
import { useUserStore } from '@/stores/userStore';
import { useOrderStore } from '@/stores/orderStore';
import * as echarts from 'echarts';

const plantStore = usePlantStore();
const userStore = useUserStore();
const orderStore = useOrderStore();

const plantCount = computed(() => plantStore.plants.length);
const userCount = computed(() => userStore.users.length);
const orderCount = computed(() => orderStore.orders.length);

const chartRef = ref(null);

onMounted(() => {
  const chart = echarts.init(chartRef.value);

  const categoryMap = {};
  plantStore.plants.forEach(plant => {
    if (categoryMap[plant.category]) {
      categoryMap[plant.category]++;
    } else {
      categoryMap[plant.category] = 1;
    }
  });

  const categories = Object.keys(categoryMap);
  const values = Object.values(categoryMap);

  const option = {
    xAxis: {
      type: 'category',
      data: categories
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: values,
        type: 'bar'
      }
    ]
  };

  chart.setOption(option);
});
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
}

.chart-card {
  height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
